package cn.stylefeng.guns.modular.biz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.modular.biz.entity.*;
import cn.stylefeng.guns.modular.biz.mapper.*;
import cn.stylefeng.guns.modular.biz.pojo.request.PrWeightRecodsCoalQuantityRequest;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.guns.modular.biz.enums.PrWeightRecodsExceptionEnum;
import cn.stylefeng.guns.modular.biz.pojo.request.PrWeightRecodsRequest;
import cn.stylefeng.guns.modular.biz.service.PrWeightRecodsService;
import cn.stylefeng.roses.kernel.db.api.factory.PageFactory;
import cn.stylefeng.roses.kernel.db.api.factory.PageResultFactory;
import cn.stylefeng.roses.kernel.db.api.pojo.page.PageResult;
import cn.stylefeng.roses.kernel.sys.modular.user.entity.SysUser;
import cn.stylefeng.roses.kernel.sys.modular.user.mapper.SysUserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.List;
import java.math.BigDecimal;

/**
 * 进场煤分摊记录业务实现层
 *
 * @author 张朋飞
 * @since 2024/10/11 16:57
 */
@Service
public class PrWeightRecodsServiceImpl extends ServiceImpl<PrWeightRecodsMapper, PrWeightRecods> implements PrWeightRecodsService {

    @Resource
    private PrWeightSumOrderMapper prWeightSumOrderMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private WmInventoryQtyMapper wmInventoryQtyMapper;
    @Resource
    private WmMdWarehouseManageMapper wmMdWarehouseManageMapper;
    @Resource
    private WmMdLayerMapper wmMdLayerMapper;

    @Override
    public void add(PrWeightRecodsRequest prWeightRecodsRequest) {
        PrWeightRecods prWeightRecods =null;
       List<PrWeightRecodsCoalQuantityRequest> list=prWeightRecodsRequest.getCoalQuantitys();
       if(ObjectUtil.isNotEmpty(list)){
        for (PrWeightRecodsCoalQuantityRequest coalQuantity :list) {
            if(ObjectUtil.isAllNotEmpty(coalQuantity.getInWeight(),coalQuantity.getLayerCode(),coalQuantity.getManagerCode())){
            prWeightRecods=new PrWeightRecods();//新建对象
            BeanUtil.copyProperties(prWeightRecodsRequest, prWeightRecods);
            PrWeightSumOrder prWeightSumOrder=prWeightSumOrderMapper.selectById(prWeightRecods.getWtSumId());
//            prWeightRecods.setWtSumId(prWeightSumOrder.getWtSumId());
            //区域管理编码
            prWeightRecods.setManagerCode(coalQuantity.getManagerCode());
            //层高代码
            prWeightRecods.setLayerCode(coalQuantity.getLayerCode());
            //入堆重量
            prWeightRecods.setInWeight(new BigDecimal(coalQuantity.getInWeight()));
            //预报总热值
            Float forecastSumQnetar=  Float.parseFloat(prWeightRecods.getForecastQnetar())*Float.parseFloat(coalQuantity.getInWeight());
            prWeightRecods.setForecastSumQnetar(String.format("%.2f", forecastSumQnetar));
            //预报总干基硫分
            Float forecastSumStd=  Float.parseFloat(prWeightRecods.getForecastStd())*Float.parseFloat(coalQuantity.getInWeight());
            prWeightRecods.setForecastSumStd(String.format("%.2f", forecastSumStd));

            //更新MES计量汇总单中的预报检测信息
//            prWeightSumOrder.setForecastQnetar(String.format("%.2f", Float.parseFloat(prWeightRecods.getForecastQnetar())));
//            prWeightSumOrder.setForecastStd(String.format("%.2f", Float.parseFloat(prWeightRecods.getForecastStd())));
            prWeightSumOrder.setDelFlag("Y");
            prWeightSumOrderMapper.updateById(prWeightSumOrder);
            //保存重量记录
            boolean is_ok=  this.save(prWeightRecods);
              if(is_ok){
                  saveOrUpdateWminventoryqty(prWeightRecods);
              }
            }
        }
       }
    }

    /**
     * 保存或更新库存重量
     * 查询是否存在区域管理编码和层高代码，如果存在就更新重量、热值、干基硫分，否则插入管理编码、层高代码、重量、热值、干基硫分
     * @param prWeightRecods
     * @return
     */
    private boolean saveOrUpdateWminventoryqty(PrWeightRecods prWeightRecods){
        int counts=0;
        WmInventoryQty wmInventoryQty=  wmInventoryQtyMapper.selectOne(new LambdaQueryWrapper<>(WmInventoryQty.class)
                .eq(WmInventoryQty::getWiqCode, prWeightRecods.getManagerCode()+prWeightRecods.getLayerCode()));
        if(ObjectUtil.isEmpty(wmInventoryQty)){
            WmMdWarehouseManage wmMdWarehouseManage=wmMdWarehouseManageMapper.selectOne(new LambdaQueryWrapper<>(WmMdWarehouseManage.class).eq(WmMdWarehouseManage::getManagerCode,prWeightRecods.getManagerCode()));
            WmMdLayer wmMdLayer=wmMdLayerMapper.selectOne(new LambdaQueryWrapper<>(WmMdLayer.class).eq(WmMdLayer::getLayerCode,prWeightRecods.getLayerCode()));
            if (ObjectUtil.isAllNotEmpty(wmMdWarehouseManage,wmMdLayer)) {
                wmInventoryQty=new WmInventoryQty();
                wmInventoryQty.setWiqCode(prWeightRecods.getManagerCode()+prWeightRecods.getLayerCode());//管理代码与层高
                wmInventoryQty.setWiqName(wmMdWarehouseManage.getManagerName()+wmMdLayer.getLayerName());//管理代码与层高名称
                wmInventoryQty.setWiqManagerCode(prWeightRecods.getManagerCode());//区域管理编码
                wmInventoryQty.setWiqManagerHeightCode(prWeightRecods.getLayerCode());//层高代码
                wmInventoryQty.setWiqMass(prWeightRecods.getInWeight());//入堆重量
                wmInventoryQty.setWiqQnetar(new BigDecimal(prWeightRecods.getForecastSumQnetar()));//总热值
                wmInventoryQty.setWiqStd(new BigDecimal(prWeightRecods.getForecastSumStd()));//总干基硫分
                counts=wmInventoryQtyMapper.insert(wmInventoryQty);
            }
        }else{
            wmInventoryQty.setWiqMass(wmInventoryQty.getWiqMass().add(prWeightRecods.getInWeight()));
            wmInventoryQty.setWiqQnetar(wmInventoryQty.getWiqQnetar().add(new BigDecimal(prWeightRecods.getForecastSumQnetar())));
            wmInventoryQty.setWiqStd(wmInventoryQty.getWiqStd().add(new BigDecimal(prWeightRecods.getForecastSumStd())));
            counts=wmInventoryQtyMapper.updateById(wmInventoryQty);
        }
        return counts > 0;

    }


    @Override
    public void del(PrWeightRecodsRequest prWeightRecodsRequest) {
        PrWeightRecods prWeightRecods = this.queryPrWeightRecods(prWeightRecodsRequest);
        this.removeById(prWeightRecods.getPwrId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(PrWeightRecodsRequest prWeightRecodsRequest) {
        this.removeByIds(prWeightRecodsRequest.getBatchDeleteIdList());
    }

    @Override
    public void edit(PrWeightRecodsRequest prWeightRecodsRequest) {
        PrWeightRecods prWeightRecods = this.queryPrWeightRecods(prWeightRecodsRequest);
        BeanUtil.copyProperties(prWeightRecodsRequest, prWeightRecods);
        this.updateById(prWeightRecods);
    }

    @Override
    public PrWeightRecods detail(PrWeightRecodsRequest prWeightRecodsRequest) {
        return this.queryPrWeightRecods(prWeightRecodsRequest);
    }



    @Override
    public PageResult<PrWeightRecods> findPage(PrWeightRecodsRequest prWeightRecodsRequest) {
        // 创建查询条件
        LambdaQueryWrapper<PrWeightRecods> wrapper = createWrapper(prWeightRecodsRequest);
        // 分页查询
        Page<PrWeightRecods> pageList = this.page(PageFactory.defaultPage(), wrapper);
        // 遍历查询结果
        for (PrWeightRecods record : pageList.getRecords()) {

            // 根据wtSumId查询PrWeightSumOrder
            PrWeightSumOrder prWeightSumOrder=prWeightSumOrderMapper.selectById(record.getWtSumId());
            // 设置wtSumId
            record.setWtSumId(prWeightSumOrder.getWtSumId());

            // 根据createUser查询SysUser
            SysUser sysUser =sysUserMapper.selectById(record.getCreateUser());
            // 设置createUserName
            record.setCreateUserName(sysUser.getRealName());

            // 根据managerCode查询WmMdWarehouseManage
            WmMdWarehouseManage wmMdWarehouseManage=wmMdWarehouseManageMapper.selectOne(new LambdaQueryWrapper<>(WmMdWarehouseManage.class).eq(WmMdWarehouseManage::getManagerCode,record.getManagerCode()));
            // 设置managerCode
            record.setManagerCode(wmMdWarehouseManage.getManagerName());

            // 根据layerCode查询WmMdLayer
            WmMdLayer wmMdLayer=wmMdLayerMapper.selectOne(new LambdaQueryWrapper<>(WmMdLayer.class).eq(WmMdLayer::getLayerCode,record.getLayerCode()));
            // 设置layerCode
            record.setLayerCode(wmMdLayer.getLayerName());

        }

        return PageResultFactory.createPageResult(pageList);
    }

    @Override
    public List<PrWeightRecods> findList(PrWeightRecodsRequest prWeightRecodsRequest) {
        LambdaQueryWrapper<PrWeightRecods> wrapper = this.createWrapper(prWeightRecodsRequest);
        return this.list(wrapper);
    }

    /**
     * 获取信息
     *
     * @author 张朋飞
     * @since 2024/10/11 16:57
     */
    private PrWeightRecods queryPrWeightRecods(PrWeightRecodsRequest prWeightRecodsRequest) {
        PrWeightRecods prWeightRecods = this.getById(prWeightRecodsRequest.getPwrId());
        if (ObjectUtil.isEmpty(prWeightRecods)) {
            throw new ServiceException(PrWeightRecodsExceptionEnum.PR_WEIGHT_RECODS_NOT_EXISTED);
        }
        return prWeightRecods;
    }

    /**
     * 创建查询wrapper
     *
     * @author 张朋飞
     * @since 2024/10/11 16:57
     */
    private LambdaQueryWrapper<PrWeightRecods> createWrapper(PrWeightRecodsRequest prWeightRecodsRequest) {
        LambdaQueryWrapper<PrWeightRecods> queryWrapper = new LambdaQueryWrapper<>();

        Long pwrId = prWeightRecodsRequest.getPwrId();
        queryWrapper.eq(ObjectUtil.isNotNull(pwrId), PrWeightRecods::getPwrId, pwrId);

        String wtSumId = prWeightRecodsRequest.getWtSumId();
        queryWrapper.like(ObjectUtil.isNotEmpty(wtSumId), PrWeightRecods::getWtSumId, wtSumId);

        BigDecimal weight = prWeightRecodsRequest.getWeight();
        queryWrapper.eq(ObjectUtil.isNotNull(weight), PrWeightRecods::getWeight, weight);

        String forecastQnetar = prWeightRecodsRequest.getForecastQnetar();
        queryWrapper.like(ObjectUtil.isNotEmpty(forecastQnetar), PrWeightRecods::getForecastQnetar, forecastQnetar);

        String forecastStd = prWeightRecodsRequest.getForecastStd();
        queryWrapper.like(ObjectUtil.isNotEmpty(forecastStd), PrWeightRecods::getForecastStd, forecastStd);

        String qnetar = prWeightRecodsRequest.getQnetar();
        queryWrapper.like(ObjectUtil.isNotEmpty(qnetar), PrWeightRecods::getQnetar, qnetar);

        String std = prWeightRecodsRequest.getStd();
        queryWrapper.like(ObjectUtil.isNotEmpty(std), PrWeightRecods::getStd, std);

        String managerCode = prWeightRecodsRequest.getManagerCode();
        queryWrapper.like(ObjectUtil.isNotEmpty(managerCode), PrWeightRecods::getManagerCode, managerCode);

        String layerCode = prWeightRecodsRequest.getLayerCode();
        queryWrapper.like(ObjectUtil.isNotEmpty(layerCode), PrWeightRecods::getLayerCode, layerCode);

        BigDecimal inWeight = prWeightRecodsRequest.getInWeight();
        queryWrapper.eq(ObjectUtil.isNotNull(inWeight), PrWeightRecods::getInWeight, inWeight);

        String forecastSumQnetar = prWeightRecodsRequest.getForecastSumQnetar();
        queryWrapper.like(ObjectUtil.isNotEmpty(forecastSumQnetar), PrWeightRecods::getForecastSumQnetar, forecastSumQnetar);

        String forecastSumStd = prWeightRecodsRequest.getForecastSumStd();
        queryWrapper.like(ObjectUtil.isNotEmpty(forecastSumStd), PrWeightRecods::getForecastSumStd, forecastSumStd);

        String sumQnetar = prWeightRecodsRequest.getSumQnetar();
        queryWrapper.like(ObjectUtil.isNotEmpty(sumQnetar), PrWeightRecods::getSumQnetar, sumQnetar);

        String sumStd = prWeightRecodsRequest.getSumStd();
        queryWrapper.like(ObjectUtil.isNotEmpty(sumStd), PrWeightRecods::getSumStd, sumStd);


        return queryWrapper;
    }

}
